//
//  CustomView.m
//  点击触摸
//
//  Created by 伍银荣 on 2021/7/5.
//  Copyright © 2021 com.WYR. All rights reserved.
//

#import "CustomView.h"

@implementation CustomView

//手指触摸到这个view的时候调用
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSLog(@"%s",__func__);
    //获取触摸对象
    UITouch *t = touches.anyObject;
    //获取当前点的位置(locationInView:相对的view不同他的坐标也不同)这里必须是t.view.superview
    CGPoint currentPoint = [t locationInView:t.view.superview];
    //设置CustomView的center为当前点的位置
    self.center = currentPoint;
    NSLog(@"currentPoint = %@",NSStringFromCGPoint(currentPoint));
    NSLog(@"center = %@",NSStringFromCGPoint(self.center));
}

//手指移动这个view的时候调用
-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSLog(@"%s",__func__);
    //方法一:
    //获取触摸对象
//    UITouch *t = touches.anyObject;
//    //获取当前点的位置
//    CGPoint currentPoint = [t locationInView:t.view.superview];
//    //设置当前CustomView的center等于当前点的位置
//    self.center = currentPoint;
    
    //方法二:可以获取手指移动view时的偏移量
    //获取触摸对象
    UITouch *t = touches.anyObject;
    //获取当前点的位置
    CGPoint currentPoint = [t locationInView:t.view.superview];
    //获取上一点的位置
    CGPoint lastPoint = [t previousLocationInView:t.view.superview];
    //获取两点间x的偏移量
    CGFloat offsetX = currentPoint.x  - lastPoint.x;
    //获取两点间y的偏移量
    CGFloat offsetY = currentPoint.y - lastPoint.y;
    //设置CustomView的center等于原本view的中心点加上偏移量
    self.center = CGPointMake(self.center.x + offsetX, lastPoint.y + offsetY);
}



/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
